try {
  require('ts-node/register');
} catch (error) {
  console.warn('ts-node/register 加载失败，继续以 JS 模式运行。', error?.message || error);
}

const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const { testPrismaConnection } = require('./config/prisma');
const { autoPublishJob } = require('./jobs/autoPublishJob');
const { autoPublishLocalServicesJob } = require('./jobs/autoPublishLocalServicesJob');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
const listingRoutes = require('./routes/listings');
const adminRoutes = require('./routes/admin');
const chatRoutes = require('./routes/chat');
const packageRoutes = require('./routes/packages');
const orderRoutes = require('./routes/orders');
const paymentRoutes = require('./routes/payments');
const contactViewRoutes = require('./routes/contact-view');
const localServiceRoutes = require('./routes/local-services');
const serviceDepositRoutes = require('./routes/service-deposits');
const exposureRoutes = require('./routes/exposure');
const wechatOfficialRoutes = require('./routes/wechat-official');

const app = express();
const PORT = process.env.PORT || 3000;

// 允许在反向代理环境中获取真实客户端IP
app.set('trust proxy', true);

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
app.use('/api/v1/auth', authRoutes);
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/listings', listingRoutes);
app.use('/api/v1/admin', adminRoutes);
app.use('/api/v1/chat', chatRoutes);
app.use('/api/v1/packages', packageRoutes);
app.use('/api/v1/orders', orderRoutes);
app.use('/api/v1/payments', paymentRoutes);
app.use('/api/v1/contact-view', contactViewRoutes);
app.use('/api/v1/local-services', localServiceRoutes);
app.use('/api/v1/service-deposits', serviceDepositRoutes);
app.use('/api/v1/exposure', exposureRoutes);
app.use('/api/v1/wechat-official', wechatOfficialRoutes);

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  
  // 开发环境返回详细错误信息
  if (process.env.NODE_ENV === 'development') {
    res.status(500).json({
      success: false,
      message: err.message,
      stack: err.stack
    });
  } else {
    // 生产环境返回通用错误信息
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 启动服务器
async function startServer() {
  try {
    // 测试数据库连接
    const dbConnected = await testPrismaConnection();
    if (!dbConnected) {
      console.error('❌ 数据库连接失败，服务器启动中止');
      process.exit(1);
    }

    app.listen(PORT, () => {
      console.log(`🚀 服务器启动成功`);
      console.log(`📍 服务地址: http://localhost:${PORT}`);
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);

      // 启动自动发布定时任务
      autoPublishJob.start();
      console.log(`⏰ 自动发布定时任务已启动`);
      
      // 启动本地服务自动发布定时任务
      autoPublishLocalServicesJob.start();
      console.log(`⏰ 本地服务自动发布定时任务已启动`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  autoPublishJob.stop();
  autoPublishLocalServicesJob.stop();
  console.log('⏰ 自动发布定时任务已停止');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  autoPublishJob.stop();
  autoPublishLocalServicesJob.stop();
  console.log('⏰ 自动发布定时任务已停止');
  process.exit(0);
});

startServer();

module.exports = app;
